<template>
	<div>
		<h3 class="scoreStateTitle">成绩概览</h3>
		<div class="score-distribution">
		  <!-- 分数段分布部分 -->
		  <div class="distribution-section anchor-offset" id="fractional-distribution">
			  <h3 class="header-with-select">分数段分布图表/表格</h3>
			  <div class="segment-control">
				<span class="label">分数段默认为：</span>
				<div class="buttoncontent">
					<el-input v-model="segment"></el-input> <i>分/段</i>
				</div>
				<div>，分数段默认上限为最高分，下限为最低分。</div>
				<el-button type="primary" size="small" @click="handleSegmentChange">
				  确定
				</el-button>
			  </div>
		    
		    <!-- 图表展示 -->
		    <div class="chart-container" v-if="scorerangedata.length > 0">
		      <div ref="chartRef" style="width: 100%; height: 400px"></div>
		    </div>
        <div v-else style="line-height: 60px;width:100%;color: #909399;text-align: center;font-size:14px;">暂无数据</div>
		    <!-- 表格展示 -->
		    <el-table 
		      :data="scorerangedata" 
		      border 
		      stripe
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%"
		    >
        <el-table-column label="全体/班级" align="center">
            <template  slot-scope="scope">
                {{scope.row.type==0?'全体':'班级'}}
            </template>
        </el-table-column>
         <!-- 动态生成列：遍历 distributions -->
        <el-table-column
          v-for="(scored, index) in scorerangedata[0].distributions"
          :key="index"
          :label="`${scored.rangeStart} - ${scored.rangeEnd}`"
        >
          <!-- 固定列：人数 -->
          <el-table-column label="人数" align="center">
            <template #default="{ row }">
              <!-- 计算当前行的总人数 -->
              {{ row.distributions[index].currentCount }}
            </template>
          </el-table-column>

          <!-- 固定列：累计 -->
          <el-table-column label="累计" align="center">
            <template #default="{ row }">
              <!-- 计算当前行的累计总数 -->
              {{ row.distributions[index].accumulatedCount }}
            </template>
          </el-table-column>
        </el-table-column>
		      <!-- <el-table-column prop="className" label="班级" align="center" /> -->
          <!-- <el-table-column
						v-for="(question, index) in studentlist[0].smallQuestions || []"
						:key="question.questionNumber"
						:label="question.name+question.questionNumber">
                            <template slot-scope="scope">
                                <b style="display:block;width:100%;height:42px;cursor:pointer;line-height:42px;"
                                    @click="handleCellClick(scope.row.smallQuestions[index],scope.row.paperImages)">
                                    {{ scope.row.smallQuestions[index].score }}
                                </b>
                            </template>
                        </el-table-column> -->
            
		      <el-table-column prop="maxScore" label="最高分" align="center">
		        <!-- <template slot-scope="scope">
		          {{ formatNumber(scope.row.maxScore) }}
		        </template> -->
		      </el-table-column>
		      <el-table-column prop="minScore" label="最低分" align="center">
		        <!-- <template slot-scope="scope">
		          {{ formatNumber(scope.row.minScore) }}
		        </template> -->
		      </el-table-column>
		      <el-table-column label="平均分" align="center">
		        <template slot-scope="scope">
		          {{ formatNumber(scope.row.avgScore) }}
		        </template>
		      </el-table-column>
		      <el-table-column prop="stdDeviation" label="标准差" align="center">
		        <!-- <template slot-scope="scope">
		          {{ formatNumber(scope.row.stdDeviation) }}
		        </template> -->
		      </el-table-column>
		    </el-table>
		  </div>
		
		  <!-- 箱线图部分 -->
		  <!-- <div class="box-plot-section">
		    <div class="header-with-select">
		      <h3>2.2.2箱线图</h3>
		    </div>
		    </br>
		    <div class="chart-container">
		      <div ref="boxPlotRef" style="width: 100%; height: 400px"></div>
		    </div>
		  </div> -->
		
		  <!--  2.2.3空白率-->
		  <!-- <div class="blank-rate-section">
		    <div class="header-with-select">
		      <h3>2.2.3空白率分布</h3>
		    </div>
		    <el-table 
		      :data="blankRateData" 
		      border 
		      stripe
		      style="width: 100%"
		    >
		      <el-table-column prop="range" label="空白率" align="center" width="120">
		        <template slot-scope="scope">
		          {{ scope.row.start }}%-{{ scope.row.end }}%
		        </template>
		      </el-table-column>
		      <el-table-column prop="students" label="名单" align="center">
		        <template slot-scope="scope">
		          {{ scope.row.students.join('、') || '-' }}
		        </template>
		      </el-table-column>
		    </el-table>
		  </div> -->
		
		  <!--  2.2.4两分五率-->
		  <div class="score-rate-section anchor-offset" id="Two-point-five-rate" style="margin-bottom:24px;">
		    <h3 class="header-with-select">两分五率/排名</h3>
		    <div class="statistics-table">
		      <el-table 
		        :data="twopointfiveratedata" 
		        border 
		        stripe
		        :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		        class="custom-table"
		        tooltip-effect="dark"
		        style="width: 100%"
		      >
            <el-table-column  label="全体/班级" align="center" >
              <template  slot-scope="scope">
                {{scope.row.type==0?'全体':'班级'}}
              </template>
            </el-table-column>
		        <el-table-column prop="submitCount" label="人数" align="center" />
		        <el-table-column prop="highestScore" label="最高分" align="center" />
		        <el-table-column prop="lowestScore" label="最低分" align="center" />
            <el-table-column prop="lowestScore" label="平均分" align="center" />
            <el-table-column prop="lowestScore" label="标准差" align="center" />
		        <el-table-column label="满分率" align="center">
		          <el-table-column prop="fullScoreCount" label="人次" align="center" />
		          <el-table-column prop="fullScoreRate" label="占比" align="center" />
		          <el-table-column prop="fullScoreRateRank" label="排名" align="center" />
		        </el-table-column>
		        <el-table-column label="优秀率" align="center">
		          <el-table-column prop="excellentCount" label="人数" align="center" />
		          <el-table-column prop="excellentRate" label="占比" align="center" />
              <el-table-column prop="excellentRateRank" label="排名" align="center" />
		        </el-table-column>
		        <el-table-column label="良好率 " align="center">
		          <el-table-column prop="goodCount" label="人数" align="center" />
		          <el-table-column prop="goodRate" label="占比" align="center" />
              <el-table-column prop="goodRateRank" label="排名" align="center" />
		        </el-table-column>
		        <el-table-column label="及格率" align="center">
		          <el-table-column prop="passCount" label="人数" align="center" />
		          <el-table-column prop="passRate" label="占比" align="center" />
              <el-table-column prop="passRateRank" label="排名" align="center" />
		        </el-table-column>
		        <el-table-column label="低分率" align="center">
		          <el-table-column prop="lowCount" label="人数" align="center" />
		          <el-table-column prop="lowRate" label="占比" align="center" />
              <el-table-column prop="lowRateRank" label="排名" align="center" />
		        </el-table-column>
		      </el-table>
		    </div>
		  </div>
		<!--  2.2.3空白率-->
    <div class="score-rate-section anchor-offset" id="student-distribution">
		    <h3 class="header-with-select">提交率/空白率对比</h3>
		    <el-table 
		      :data="submittedcomparisonblankrateslist" 
		      border 
		        stripe
		        :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		        class="custom-table"
		        tooltip-effect="dark"
		        style="width: 100%"
		    >
		      <el-table-column prop="name" label="全体/班级" align="center" />
		      <el-table-column prop="totalSubmitNum" label="人数" align="center" />
          <el-table-column prop="submitRate" label="提交率" align="center" />
          <el-table-column prop="submitNum" label="排名" align="center" />
          <!-- <el-table-column prop="range" label="空白率" align="center" /> -->
          <!-- <el-table-column prop="range" label="排名 " align="center" /> -->
		    </el-table>
		  </div>
		  <!-- 2.2.5 学优生/学困生分布 -->
		  <div class="student-distribution-section anchor-offset" id="student-distribution1">
		    <h3 class="header-with-select">学优生/学困生分布<span>学优生/学困生分布（学优生为作业得分率超过85%，学困生作业得分率低于40%）</span></h3>
		    <div class="statistics-table">
		      <el-table 
		        :data="orthogenicsdistributionlist" 
		        border 
		        stripe
		        :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		        class="custom-table"
		        tooltip-effect="dark"
		        style="width: 100%"
		      >
          <el-table-column prop="name"  label="全体/班级" align="center" />
		        <!-- <el-table-column prop="className" label="班级" align="center" /> -->
		        <el-table-column label="学优生" align="center">
		          <el-table-column prop="excellentCount" label="学优生" align="center" />
		          <el-table-column prop="excellentRate" label="占比" align="center" />
		          <el-table-column prop="excellentAvg" label="均分" align="center" />
		        </el-table-column>
		        <el-table-column label="学困生" align="center">
		          <el-table-column prop="poorCount" label="学困生" align="center" />
		          <el-table-column prop="poorRate" label="占比" align="center" />
		          <el-table-column prop="poorAvg" label="均分" align="center" />
		        </el-table-column>
		      </el-table>
		    </div>
		  </div> 
		</div>
	</div>
</template>

<script>
import { getScoreDistribution, getGradeTwopointfiverate,submittedcomparisonblankrates,orthogenicsdistribution } from '@/api/grade'
import * as echarts from 'echarts'

export default {
  name: 'ScoreDistribution',
  props: {
    examId: {
      type: [String, Number],
      required: true
    },
    classIds: {
      type: [String, Number],
      required: true
    },
    gradeId: {
      type: [String, Number],
      required: true
    },
    subjectId: {
      type: [String, Number],
      required: true
    },
    classIds1: {
      type: [Array],
      required: true
    },
  },
  data() {
    return {
      segment:5,
      chartInstance: null,
      boxPlotChart: null,
      tableData: [{distributions:[]}],
      boxPlotData: null,
      blankRateData: [],
      scoreRateData: [],
      studentDistributionData: [],
      loading: false,
      hasLoaded: false,
      loadingPromise: null,
      sutdentDistributionDataname:[],
      scorerangedata:[{distributions:[]}],
      twopointfiveratedata:[],
      submittedcomparisonblankrateslist:[],
      orthogenicsdistributionlist:[]
    }
  },
  mounted() {
    this.scorerangeTable()
    this.gradetwopointfiveratebtab()
    this.submittedcomparisonblankratesdate()
    this.orthogenicsdistributiondata()
  },
  beforeDestroy() {
    // 清理图表实例和事件监听
    if (this.boxPlotChart) {
      window.removeEventListener('resize', this.boxPlotChart.resize)
      this.boxPlotChart.dispose()
      this.boxPlotChart = null
    }
  },
  methods: {
    // 分数段分布图标、表格
    async scorerangeTable() {
      this.scorerangedata = []
        try {
          const res = await getScoreDistribution(
            Number(this.examId), 
            String(this.classIds),
            String(this.segment)
          )
          if (res.code === 200) {
            console.info('scorerangeTable',res)
            this.scorerangedata = res.data
            this.$nextTick(() => {
              // 先销毁旧图表
              if (this.chartInstance) {
                this.chartInstance.dispose();
                this.chartInstance = null;
              }
              // 重新初始化图表
              this.updateChart(res.data);
            });
          } else {
            throw new Error(res.message)
          }
        } catch (error) {
          console.error('加载成绩概览失败:', error)
          throw error  // 向上传递错误，让 loadData 统一处理
        }
      },
      //年级两份五率
      async gradetwopointfiveratebtab(){
        this.twopointfiveratedata = []
        try {
          const res = await getGradeTwopointfiverate(
            Number(this.examId), 
            this.classIds1,
            this.gradeId,
            this.subjectId
          )
          if (res.code === 200) {
            console.info('scorerangeTable',res)
            this.twopointfiveratedata = res.data
            // this.scorerangedata = res.data
            // this.updateChart(res.data);
          } else {
            throw new Error(res.message)
          }
        } catch (error) {
          console.error('加载成绩概览失败:', error)
          throw error  // 向上传递错误，让 loadData 统一处理
        }
        
      },
      //提交率空白率对比 
      async submittedcomparisonblankratesdate(){
        this.submittedcomparisonblankrateslist = []
        try {
          const res = await submittedcomparisonblankrates(
            Number(this.examId), 
            String(this.classIds)
          )
          if (res.code === 200) {
            console.info('scorerangeTable',res)
            this.submittedcomparisonblankrateslist = res.data
            // this.scorerangedata = res.data
            // this.updateChart(res.data);
          } else {
            throw new Error(res.message)
          }
        } catch (error) {
          console.error('加载成绩概览失败:', error)
          throw error  // 向上传递错误，让 loadData 统一处理
        }
      },
      //学优生学困生分布
      async orthogenicsdistributiondata(){
        this.orthogenicsdistributionlist = []
        try {
          const res = await orthogenicsdistribution(
            Number(this.examId), 
            String(this.classIds)
          )
          if (res.code === 200) {
            console.info('scorerangeTable',res)
            this.orthogenicsdistributionlist = res.data
            // this.scorerangedata = res.data
            // this.updateChart(res.data);
          } else {
            throw new Error(res.message)
          }
        } catch (error) {
          console.error('加载成绩概览失败:', error)
          throw error  // 向上传递错误，让 loadData 统一处理
        }
      },
    // async loadData() {
    //   // 防止重复加载
    //   if (this.loadingPromise) {
    //     return this.loadingPromise;
    //   }

    //   // 如果已经加载过且有数据，则不重复加载
    //   if (this.hasLoaded && this.studentDistributionData.length > 0) {
    //     return;
    //   }

    //   try {
    //     this.loading = true;
        
    //     // 保存 Promise 引用
    //     this.loadingPromise = Promise.all([
    //       getScoreDistribution(this.examId, this.classIds, this.segment),
    //       // getScoreRates(this.examId, this.classId),
    //       // getStudentDistribution(this.examId, this.classId)
    //     ]);

    //     // const [distRes, scoreRateRes, studentDistRes] = await this.loadingPromise;
    //     const [distRes] = await this.loadingPromise;
    //     console.info('distRes',distRes)
    //     if (distRes && distRes.code === 200) {
          
    //       this.tableData = distRes.data
    //       console.info('tableData',this.tableData)
    //       let echartlist = distRes.data.filter(item => item.type == 1);
    //       this.updateChart(echartlist[0].distributions);
    //     }

    //     // if (scoreRateRes && scoreRateRes.code === 200) {
    //     //   this.scoreRateData = scoreRateRes.data;
    //     // }

    //     // if (studentDistRes && studentDistRes.code === 200) {
    //     //   this.studentDistributionData = studentDistRes.data;
    //     //   this.sutdentDistributionDataname = studentDistRes.data.filter(item => item.type == 1);
    //     // }

    //     this.hasLoaded = true;

    //   } catch (error) {
    //     console.error('加载数据失败:', error);
    //     this.$message.error('加载成绩分布数据失败');
    //   } finally {
    //     this.loading = false;
    //     this.loadingPromise = null;
    //   }
    // },
  
    
    updateChart(dataList) {
      // 检查 DOM 元素是否存在
		if (!this.$refs.chartRef) {
			console.warn('Chart ref not found');
			return;
		}

		// 初始化 ECharts 实例
		if (!this.chartInstance) {
			this.chartInstance = echarts.init(this.$refs.chartRef);
		}

		// 防御性代码：确保 data 存在且结构正确
		if (!dataList || dataList.length === 0) {
			console.warn('No data available');
			return;
		}
      // dataList 是 API 返回的 data 数组，包含三个项目的数据
      const seriesData = dataList.map(item => ({
        name: item.name, // "全体", "002", "001"
        type: 'line',    // 改为折线图
        data: item.distributions.map(d => d.currentCount),
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        label: {
          show: true,
          formatter: '{c}人'
        }
      }));

      // 使用第一个项目的 distributions 作为 xAxis 数据（假设所有项目的区间相同）
      const xAxisData = dataList[0].distributions.map(
        d => `${d.rangeStart}-${d.rangeEnd}分`
      );

      const option = {
        title: {
          text: '分数段人数分布',
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            return params.map(p => {
              return `${p.seriesName}<br/>${p.name}: ${p.value}人`;
            }).join('<br/>');
          }
        },
        legend: {
          data: dataList.map(item => item.name),
          top: 40
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            interval: 0,
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '人数',
          minInterval: 1,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: seriesData,
        color: ['#295CFF', '#FF7D00', '#00B42A'] // 为三条线设置不同颜色
      };

      this.chartInstance.setOption(option)
    },
    handleSegmentChange() {
      // 分段改变时需要重新加载
      this.hasLoaded = false;
      this.scorerangeTable()
    },
    
    handleResize() {
      this.chartInstance.resize()
    },
    
    formatNumber(value) {
      return Number(value).toFixed(2)
    }
  },
  watch: {
    // 优化 watch 逻辑
    classIds1: {
      handler(newVal, oldVal) {
        if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return;
        console.log('classIds 变化:', oldVal, '→', newVal);
        this.classIds = newVal.join(',');
        this.scorerangeTable()
        this.gradetwopointfiveratebtab()
        this.submittedcomparisonblankratesdate()
        this.orthogenicsdistributiondata()
      },
      immediate: true,  // 立即触发一次
      deep: true       // 字符串不需要深度监听
    },
    examId: {
        handler(newVal, oldVal) {
          console.info(newVal+'-----'+oldVal)
          if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return;
          this.scorerangeTable()
          this.gradetwopointfiveratebtab()
          this.submittedcomparisonblankratesdate()
          this.orthogenicsdistributiondata()
        },
        immediate: true,  // 立即触发一次
        deep: true       // 字符串不需要深度监听
      }
  }
}
</script>

<style scoped>
.score-distribution {
	background: #FFFFFF;
	box-shadow: 0 4px 16px 0 #5572921a;
	border-radius: 10px;
	padding: 24px;
	
}

.distribution-section,
.box-plot-section {
  margin-bottom:20px;
}

.box-plot-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}

.header-with-select{
	font-size:16px;
	color:#2A303B;
	margin-bottom:14px;
}
.header-with-select span{
  font-size:12px;
  color:#999;
  font-weight:normal;
  padding-left:10px;
}
.segment-control {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 615px;
  height: 42px;
  background: rgba(41, 92, 255,0.04);
  border: 1px solid rgba(41, 92, 255,0.2);
  border-radius: 4px;
  margin:0 auto;
  font-size:14px;
}
.buttoncontent{
	box-sizing: border-box;
	width:100px;
	height:22px;
	border-radius:20px;
	display: flex;
	align-items: center;
	background:#fff;
	padding:0 8px;
	color:#5B6371
}
.buttoncontent i{
	font-style:normal;
	color:#B3B8C2;
	font-size:12px;
	line-height:22px;
}
.buttoncontent >>> .el-input{
	width:50px;
	height:22px;
	border:none;
	background:none;
	text-align: center;
}
.buttoncontent >>> .el-input__inner{
	border:none;
	background:none;
	height:22px;
	margin:0;
	padding:0;
	font-weight: bold;
}
.segment-control >>> .el-button{
	width: 58px;
	height: 22px;
	background: #295CFF;
	border-radius: 11px;
	color:#fff;
	border:none;
	line-height:22px;
	padding:0;
	margin-left:35px;
}
.label {
  color: #606266;
  font-size: 14px;
}
.chart-container {
  margin: 20px 0;
  padding: 20px;
  border-radius: 4px;
}
.highlight-count {
  color: #409EFF;
  font-weight: bold;
}
.blank-rate-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}
.score-rate-section {
  background: #fff;
  border-radius: 4px;
}
.student-list {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}
.student-distribution-section {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  margin-top:24px;
}
.scoreStateTitle{
	font-size:18px;
	color:#295CFF;
	line-height:45px;
	font-weight: normal;
	position:relative;
	padding-left:25px;
  font-weight: bold;
}
.scoreStateTitle:after{
	content:'';
	width: 14px;
	height: 14px;
	opacity: 0.5;
	background: #295CFF;
	border-radius:14px;
	position:absolute;
	left:0;
	top:15px;
}
.scoreStateTitle::before{
	content:'';
	width: 8px;
	height: 8px;
	opacity: 0.2;
	background: #295CFF;
	border-radius:14px;
	position:absolute;
	left:10px;
	top:23px;
}
.custom-table {
  width: 100%;
  border: 1px solid rgba(216,228,240,1);
  border-radius:10px;
  border-right: none;
  border-bottom:none;
  margin-top:0;
}
/* 自定义表格内部元素的样式 */
.custom-table >>> .el-table__header-wrapper th {
  background-color: rgb(232, 240, 250);
  height:42px;
  padding:0;
  text-align: center;
  font-weight:normal
}
.custom-table >>> .el-table__row td {
  height:42px;
  padding:0;
  text-align: center;
  border-bottom:none;
  border-right:solid 1px rgba(216,228,240,1);
}
.el-table .warning-row {
	background: #ffffff;
 }
.el-table .success-row {
	background: #D8E4F0;
}
.anchor-offset {
  scroll-margin-top: 60px;
}
</style> 